package cart.api.specification;

import cart.api.vo.OrderQueryVo;
import utils.Lang;
import utils.sql.GenericSpecification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Root;

/**
 * Created by Liang Wenxu on 2017-03-14.
 */
public class OrderMainSpecification extends GenericSpecification {
    public OrderMainSpecification(OrderQueryVo example) {
        super(example);
    }

    @Override
    protected void customPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
        OrderQueryVo queryVo = (OrderQueryVo) super.example;
        if(!(Lang.isEmpty(queryVo.getShippingComfirmTimeStart())) && Lang.isEmpty(queryVo.getShippingComfirmTimeEnd())) {
            Expression expStart = cb.greaterThanOrEqualTo(root.get("shippingComfirmTime"), queryVo.getShippingComfirmTimeStart());
            Expression expEnd = cb.greaterThanOrEqualTo(root.get("shippingComfirmTime"), queryVo.getShippingComfirmTimeEnd());
            Expression expCombimed = null;
            if(!(Lang.isEmpty(queryVo.getShippingComfirmTimeStart())) && !(Lang.isEmpty(queryVo.getShippingComfirmTimeStart()))) {
                expCombimed = cb.and(expStart,expEnd);
            } else {
                if(!(Lang.isEmpty(queryVo.getShippingComfirmTimeStart()))) {
                    expCombimed = expStart;
                }
                if(!(Lang.isEmpty(queryVo.getShippingComfirmTimeEnd()))) {
                    expCombimed = expEnd;
                }
            }
            super.addExpression("shippingComfirmTime", expCombimed);
        }

        if(!Lang.isEmpty(queryVo.getStatusList())) {
            CriteriaBuilder.In inExp = cb.in(root.get("status"));
            for(String s : queryVo.getStatusList()) {
                inExp.value(s);
            }
            super.addExpression("status", inExp);
        }
    }
}
